package org.example.controller;

import org.example.exception.AppException;
import org.example.model.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Object login(@RequestBody User user,
                        HttpServletRequest request){

        //数据库根据账号查询一个用户信息，查不到返回null
        User exist = userService.query(user.getUsername());

        if(exist == null){
            throw new AppException("账号不存在");
        }
        if(!exist.getPassword().equals(user.getPassword())){
            throw new AppException("账号或密码错误");
        }
        //校验通过，创建session，并保存用户信息
        HttpSession session = request.getSession();
        session.setAttribute("user", exist);
        return null;
    }

    @GetMapping("/logout")
    public Object logout(HttpSession session){
        session.removeAttribute("user");
        return null;
    }
}
